package it.unibz.ti2.internetPizzeria.dao;

import it.unibz.ti2.internetPizzeria.persistence.HibernateUtil;

import org.hibernate.Session;
import org.hibernate.Transaction;

/**
 * Base data access object. Opening, closing database session.
 */
public abstract class BaseDAO {

	Session session = null;
	
	/**
	 * Opens new hibernate session
	 */
	public void openSession(){
		this.session = HibernateUtil.getSession();
	}	
	
	/**
	 * Uses session from another baseDAO object
	 * @param baseDAO baseDAO object sharing session 
	 */
	public void openSession(BaseDAO baseDAO){
		this.session = baseDAO.session;
	}
	
	/**
	 * Closes hibernate session
	 *
	 */
	public void closeSession() {
		if (this.session != null){
			this.session.close();
		}
	}
	
	protected void saveObject(Object obj){
		Transaction transaction = session.beginTransaction();
		session.save(obj);
		transaction.commit();
	}

	protected void deleteObject(Object obj){
		Transaction transaction = session.beginTransaction();
		session.delete(obj);
		transaction.commit();
	}
	
	protected void updateObject(Object obj){
		Transaction transaction = session.beginTransaction();
		session.update(obj);
		transaction.commit();
	}
}